package com.imesne.office.excel.write;

import com.imesne.office.excel.model.ExcelCell;
import com.imesne.office.excel.utils.ExcelKitUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 单元格操作
 * 单元格不需要判断是否追加，因为单元格都是新创建的，不支持单元格里面的内容追加
 * <p>
 * Created by liyd on 17/7/5.
 */
public class ExcelCellWriterImpl extends AbstractConfigWriter implements ExcelCellWriter {

    public Cell writeExcelTitleCell(Workbook workbook, Sheet sheet, Row row, ExcelCell excelCell) {

        Cell cell = this.writeExcelCell(workbook, sheet, row, excelCell);
        Font font = workbook.createFont();
        font.setBold(true);
        RichTextString richStringCellValue = cell.getRichStringCellValue();
        richStringCellValue.applyFont(font);
        return cell;
    }

    public Cell writeExcelCell(Workbook workbook, Sheet sheet, Row row, ExcelCell excelCell) {

        Integer cellIndex = excelCell.getCellNum() - 1;
        Cell cell = this.getCell(row, cellIndex);

        // 判断值的类型后进行强制类型转换
        if (excelCell.getValue() == null) {

            cell.setCellValue("");

        } else if (excelCell.getValue() instanceof Date) {

            // 设置日期
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateValue = dateFormat.format((Date) excelCell.getValue());
            dateValue = StringUtils.replace(dateValue, " 00:00:00", "");
            cell.setCellValue(dateValue);

        } else if (excelCell.getValue() instanceof byte[]) {

            Drawing<?> drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, cellIndex, row.getRowNum(), cellIndex + 1, row.getRowNum() + 1);
            drawing.createPicture(anchor, workbook.addPicture((byte[]) excelCell.getValue(), XSSFWorkbook.PICTURE_TYPE_JPEG));
        } else if (excelCell.getValue() instanceof String[]) {

            // 设置下拉列表
            String[] values = (String[]) excelCell.getValue();
            DataValidationHelper dvHelper = sheet.getDataValidationHelper();
            DataValidationConstraint dvConstraint = dvHelper.createExplicitListConstraint(values);
            CellRangeAddressList addressList = new CellRangeAddressList(row.getRowNum(), row.getRowNum(), cellIndex, cellIndex);
            DataValidation dataValidation = dvHelper.createValidation(dvConstraint, addressList);
            sheet.addValidationData(dataValidation);

            //默认显示
            cell.setCellValue(values[0]);
        } else {

            String value = excelCell.getValue().toString();

            boolean matcher = value.matches("^\\d+(\\.\\d+)?$");

            // 是数字并且长度小于12时，当作double处理，当长度大于等于12时数字会显示成科学计数法，所以导成字符串
            if (matcher && value.length() < 12) {
                cell.setCellValue(Double.parseDouble(value));
            } else {
                cell.setCellValue(value);
            }
        }
        if (excelCell.getWidth() != null) {
            // 设置图片所在列宽度,需要单位换算
            int pixel = ExcelKitUtils.pixel2WidthUnits(excelCell.getWidth());
            sheet.setColumnWidth(cellIndex, pixel);
        }

        if (this.getExcelWriterConfig().getExcelWriteProcessor() != null) {
            this.getExcelWriterConfig().getExcelWriteProcessor().processCell(excelCell, cell, workbook, sheet, row);
        }

        return cell;
    }

    private Cell getCell(Row row, int cellIndex) {
        ExcelWriterConfig excelWriterConfig = this.getExcelWriterConfig();
        Cell cell = null;
        if (excelWriterConfig.isAppend()) {
            cell = row.getCell(cellIndex);
        }
        if (!excelWriterConfig.isAppend() || cell == null) {
            cell = row.createCell(cellIndex);
        }
        return cell;
    }
}
